
#include "UfThreadPool.h"
#include "logging.h"

UfThreadPool::UfThreadPool() 
{
}

UfThreadPool::~UfThreadPool()
{
}

void UfThreadPool::initAll(int thread_count)
{
    mMaxCount = thread_count;
    for (int i = 0; i < thread_count; i++) {
        tools::Thread* thread = new tools::Thread(new UfWorkThread());
        mThreads.push_back(thread);
    }
}

void UfThreadPool::startAll(void* arg)
{
    std::list<tools::Thread*>::iterator it;
    for (it = mThreads.begin(); it != mThreads.end(); it++) {
        tools::Thread * thread = (*it);
        RUN_HERE();
        thread->Start(arg);
    }
}

void UfThreadPool::closeAll(UfWorkThread::RunState reason)
{
    std::list<tools::Thread*>::iterator it;
    for (it = mThreads.begin(); it != mThreads.end(); it++) {
        tools::Thread * thread = (*it);
        UfWorkThread* uft = (UfWorkThread*)thread->delegate();
        uft->Close(reason);
        thread->Stop();
        delete uft;
    }
}

void UfThreadPool::addThreadAndRun(void* arg)
{
    RUN_HERE() << "start new thread...";
    if ((int)mThreads.size() < mMaxCount) {
        tools::Thread* thread = new tools::Thread(new UfWorkThread());
        mThreads.push_back(thread);
        thread->Start(arg);
    }
    RUN_HERE() << "total thread count: " << mThreads.size();
}

int UfThreadPool::getThreadsCount()
{
    return mThreads.size();
}

int UfThreadPool::getDownloadingThreadsCount()
{
    if (mThreads.empty())
        return 0;

    int count = 0;
    std::list<tools::Thread*>::iterator it;
    for (it = mThreads.begin(); it != mThreads.end(); it++) {
        tools::Thread * thread = (*it);
        UfWorkThread* uft = (UfWorkThread*)thread->delegate();
        if (uft->isDownloading()) {
            count++;
        }
    }
    return count;
}

int UfThreadPool::getIdleThreadsCount()
{
    if (mThreads.empty())
        return 0;

    int count = 0;
    std::list<tools::Thread*>::iterator it;
    for (it = mThreads.begin(); it != mThreads.end(); it++) {
        tools::Thread * thread = (*it);
        UfWorkThread* uft = (UfWorkThread*)thread->delegate();
        if (!uft->isDownloading()) {
            count++;
        }
    }
    return count;
}





